package com.acane.instagram.feature.follow

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class FollowViewModel(
    savedStateHandle: SavedStateHandle
): ViewModel() {
    // 用户id
    val userId: String = checkNotNull(savedStateHandle[FOLLOW_ROUTE_WITH_USER_ID])
    // 显示类型
    val type: String = checkNotNull(savedStateHandle[FOLLOW_ROUTE_WITH_TYPE])
    // 当前用户信息
    private val _userInfo = MutableStateFlow<UserInfo> (UserInfo())
    val userInfo = _userInfo
    // 当前用户的关注列表
    private val _followingList = MutableStateFlow<List<UserInfo>>(emptyList())
    val followingList = _followingList
    // 当前用户的粉丝列表
    private val _followerList = MutableStateFlow<List<UserInfo>>(emptyList())
    val followerList = _followerList
    // 当前登录用户的关注列表
    private val _loginFollowingList = MutableStateFlow<List<String>>(emptyList())
    val loginFollowingList = _loginFollowingList


    // 使用 MutableStateFlow 和 map 来替代 MutableStateMap
    private val _isFollowingMap = MutableStateFlow<Map<String, Boolean>>(emptyMap())
    val isFollowingMap: StateFlow<Map<String, Boolean>> get() = _isFollowingMap

    fun setIsFollowing(userId: String, isFollowing: Boolean) {
        viewModelScope.launch {
            _isFollowingMap.value = _isFollowingMap.value.toMutableMap().apply { this[userId] = isFollowing }
        }
    }

    init {
        loadData(userId)
        getCurrentUserFollowList()
    }

    fun getCurrentUserFollowList() {
        viewModelScope.launch {
            val response = SessionManager.currentUser?.id?.let {
                MyRetrofitDatasource.getFollowingList(
                    it
                )
            }
            if (response?.data != null) {
                // 获取所有id
                _loginFollowingList.value = listOf(response.data.map { it.id }.toString())
            }
        }
    }
    fun loadData(userId: String) {
        // 加载当前用户数据
        viewModelScope.launch {
            val response = MyRetrofitDatasource.getUserById(userId)
            if (response.data != null) {
                _userInfo.value = response.data
            }
        }
        // 加载当前用户的关注列表
        viewModelScope.launch {
            val response = MyRetrofitDatasource.getFollowingList(userId)
            if (response.data != null) {
                _followingList.value = response.data
            }
        }
        // 加载当前用户的粉丝列表
        viewModelScope.launch {
            val response = MyRetrofitDatasource.getFollowerList(userId)
            if (response.data != null) {
                _followerList.value = response.data
            }
        }
    }


}